package org.dromara.xhlj.system.font;

import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.io.FileUtils;

public class FontLoader {
    private static final FontLoader INSTANCE = new FontLoader();
    private final ConcurrentMap<String, Font> fontCache = new ConcurrentHashMap<>();

    // 私有构造函数防止外部实例化
    private FontLoader() {
    }

    public static FontLoader getInstance() {
        return INSTANCE;
    }

    public Font getFontFromURL(String urlString, float fontSize, int fontStyle) throws Exception {
        // 先从缓存中获取字体
        Font cachedFont = fontCache.get(urlString);
        if (cachedFont != null) {
            return cachedFont.deriveFont(fontStyle, fontSize);
        }

        // 如果缓存中没有，则下载字体并加载
        URL url = new URL(urlString);
        String fileExtension = urlString.substring(urlString.lastIndexOf('.'));
        File tempFile = File.createTempFile("font-" + UUID.randomUUID(), fileExtension);

        try (InputStream inputStream = url.openStream()) {
            FileUtils.copyInputStreamToFile(inputStream, tempFile);
        }

        Font font;
        try (InputStream fontStream = new FileInputStream(tempFile)) {
            font = Font.createFont(Font.TRUETYPE_FONT, fontStream).deriveFont(fontStyle, fontSize);
        }

        // 删除临时文件
        Files.deleteIfExists(tempFile.toPath());

        // 缓存字体
        fontCache.put(urlString, font);

        return font;
    }
}

